from socket_server import socket
from socket_server.HttpService import Service
from socket_server.Request import Request
from socket_server.Response import Response
from socket_server.ServiceContainer import Container
from socket_server import configparser
from socket_server.Container import NotFound_Service

cf = configparser.ConfigParser()
back_log = 10
buffer_size = 1024
container = Container()


def main(host, port=5000):
    webserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    webserver.bind((host, port))
    webserver.listen(back_log)
    addr = "http://" + host + ":" + str(port)
    print(addr)
    print("waiting for request..........")
    while True:
        conn, addr = webserver.accept()
        recvdata = conn.recv(buffer_size)

        # 构建请求对象
        request = Request(recvdata.decode())
        # 跳过ico图标加载，需要可删除
        if request.get_url() == "/favicon.ico":
            continue
        url = request.get_url()
        print(url)
        Server_Container = container.get_Con(url)
        if Server_Container is None:
            try:
                cf.read("web.conf")
                value = cf.get(url)
                if value is not None:
                    value = value.split(".")
                    print(".".join(value[1:len(value)]))
                    # 动态加载模块
                    module = __import__(".".join(value[:-1]))
                    print(module)
                    # micropython有问题，micropython的__import__不支持fromlist参数。。。所以得这么写↓
                    Server_Container = getattr(getattr(getattr(module, value[1]), value[2]), value[3])()  # 返回一个对象
                    container.set_Con({url: Server_Container})
                else:
                    Server_Container = NotFound_Service.NotFound()
            except (configparser.FileNotExistError, configparser.DuplicateSectionError):
                print("文件不存在或配置项重复")
                conn.close()
                continue
        response = Response(conn)
        Server_Container.service(request, response)


if __name__ == '__main__':
    main('127.0.0.1', 8080)
